import { createSlice, PayloadAction } from '@reduxjs/toolkit'
import { User, UserProfile } from '@/types/data'
// state变量类型
export interface ProfileState {
  user: User
  editUser: UserProfile
}
export const Profile = createSlice({
  // 命名空间，在调用action的时候会默认的设置为action命令的前缀,避免冲突
  name: 'Profile',
  // 1. 定义变量(状态数据)
  initialState: {
    user: {},
    editUser: {},
  } as ProfileState,
  // 2. 定义reducers更新变量(其中函数属性名作为action，在组件中可以dispatch触发reducer函数更新状态)
  reducers: {
    setUser(state, action: PayloadAction<User>) {
      state.user = action.payload
    },
    setEditUser(state, action: PayloadAction<UserProfile>) {
      state.editUser = action.payload
    },
    marge(state, action: PayloadAction<Partial<UserProfile>>) {
      state.editUser = { ...state.editUser, ...action.payload }
    },
  },
})

// 导出action函数(组件中可以dispatch(action函数)触发reducer更新状态)
export const { setUser, setEditUser, marge } = Profile.actions

// 导出reducer(创建store使用)
export default Profile.reducer
